package com.yiwei.ydd.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spanned;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.yiwei.ydd.R;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.bean.BuyLevelBean;
import com.yiwei.ydd.api.bean.PaymentBean;
import com.yiwei.ydd.api.bean.VipOrderDetailBean;
import com.yiwei.ydd.api.model.VipOrderDetailModel;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.constant.Const;
import com.yiwei.ydd.event.BuyVipUpSuccessEvent;
import com.yiwei.ydd.util.Arith;
import com.yiwei.ydd.util.DateTime;
import com.yiwei.ydd.util.Dialog;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.Spans;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.UI;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.beecloud.BCPay;
import cn.beecloud.BeeCloud;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class VipOrderDetailActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_status)
    TextView txtStatus;
    @BindView(R.id.img_status)
    ImageView imgStatus;
    @BindView(R.id.txt_vip_type)
    TextView txtVipType;
    @BindView(R.id.txt_status_one)
    TextView txtStatusOne;
    @BindView(R.id.img_icon)
    ImageView imgIcon;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.txt_info_left)
    TextView txtInfoLeft;
    @BindView(R.id.txt_info_right)
    TextView txtInfoRight;
    @BindView(R.id.txt_title_one)
    TextView txtTitleOne;
    @BindView(R.id.txt_content_one)
    TextView txtContentOne;
    @BindView(R.id.txt_title_two)
    TextView txtTitleTwo;
    @BindView(R.id.txt_content_two)
    TextView txtContentTwo;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.txt_title_vip)
    TextView txtTitleVip;

    private Unbinder unbiner;
    private int x24;
    private String order_no;
    private VipOrderDetailModel.DatasBean totalData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_order_detail);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        txtTitle.setText("订单详情");
        x24 = getResources().getDimensionPixelSize(R.dimen.x24);
        order_no = getIntent().getStringExtra("order_no");

        getVipOrderDetail(order_no);
    }

    public void getVipOrderDetail(String order_number) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        VipOrderDetailBean bean = new VipOrderDetailBean();
        bean.order_number = order_number;
        Api.api_service.getVipOrderDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setData(result.datas);
                });
    }

    private void setData(VipOrderDetailModel.DatasBean item) {
        totalData = item;

//0：待支付，1：已关闭 2：已付款
        switch (item.status) {
            case "0":
                txtStatusOne.setText("待付款");
                imgStatus.setImageResource(R.mipmap.img_status_need_pay);
                String restTime = Util.getRestTime(Long.valueOf(item.valid_date) * 1000 - new Date().getTime());

                Spanned rest_time = Spans.with(this).font("等待买家付款\n", getResources().getDimensionPixelSize(R.dimen.x32), 0xffffffff).
                        font("剩" + restTime + "自动关闭", getResources().getDimensionPixelSize(R.dimen.x24), 0xffffffff).style(Typeface.BOLD).
                        build();
                txtStatus.setText(rest_time);
                txtInfoLeft.setText("订单编号\n下单时间");
                txtInfoRight.setText(item.order_number + "\n" + DateTime.toDateTime(Long.valueOf(item.created_at) * 1000));
                btnSubmit.setText("去付款");
                btnSubmit.setShapeStrokeColor(0xffFB5E01).setUseShape();
                break;
            case "1":
                imgStatus.setImageResource(R.mipmap.img_status_pay_close);
                txtStatusOne.setText("交易已关闭");
                txtInfoLeft.setText("订单编号\n下单时间");
                txtInfoRight.setText(item.order_number + "\n" + DateTime.toDateTime(Long.valueOf(item.created_at) * 1000));
                btnSubmit.setText("油卡充值");
                btnSubmit.setShapeStrokeColor(0xffFB5E01).setUseShape();
                break;
            case "2":
                imgStatus.setImageResource(R.mipmap.img_status_finish);
                txtStatusOne.setText("买家已付款");
                txtInfoLeft.setText("订单编号\n下单时间\n支付方式\n支付时间");
                btnSubmit.setText("删除订单");
                btnSubmit.setTextColor(0xff070707);
                btnSubmit.setShapeStrokeColor(0xffD2D2D2).setUseShape();
                String payWay = "";
                switch (item.pay_way) {
                    // 1微信 2    支付宝  5 钱包余额
                    case "1":
                        payWay = "微信支付";
                        break;
                    case "2":
                        payWay = "支付宝支付";
                        break;
                    case "5":
                        payWay = "钱包余额支付";
                        break;
                }
                txtInfoRight.setText(item.order_number + "\n" + DateTime.toDateTime(Long.valueOf(item.created_at) * 1000) + "\n" + payWay + "\n" + DateTime.toDateTime(Long.valueOf(item.pay_date) * 1000));
                break;
        }

        txtTitleVip.setText(item.name);
        txtMoney.setText("￥" + item.pay_money);
        if (item.level == null) {
            return;
        }
        Glide.with(this).load(item.level.icon).into(imgIcon);

        txtTitleOne.setText(item.level.name + "权益说明");
        txtTitleTwo.setText(item.level.name + "等级说明");
        txtContentOne.setText(getTextBottom(item.level.sale, item.level.term_sale, item.level.uolevel_rate, item.level.utlevel_rate));


        if (item.level.level.equals("2")) {
            txtContentTwo.setText(getTextBottomTips(item.level.money, item.level.up_money));
        } else if (item.level.level.equals("3")) {
            txtContentTwo.setText(getTextBottomTipsThree(item.level.money, item.level.up_money, item.level.diff_money));
        }
    }


    private Spanned getTextBottom(String sale, String term_sale, String uolevel_rate, String utlevel_rate) {
        return Spans.with(this).font("1.即时充值可享受最低", x24, 0xff333333).
                font(Float.valueOf(sale) / 10 + "", x24, 0xffFB5E01).style(Typeface.BOLD).
                font("折优惠；\n2.购买加油套餐最多可享受赠送", x24, 0xff333333).
                font(term_sale+ "%", x24, 0xffFB5E01).style(Typeface.BOLD).
                font("的充值返现；\n3.分享推荐拿佣金提成：一级奖励", x24, 0xff333333).
                font(uolevel_rate + "%", x24, 0xffFB5E01).style(Typeface.BOLD).
                font("，二级奖励", x24, 0xff333333).
                font(utlevel_rate + "%", x24, 0xffFB5E01).style(Typeface.BOLD).
                font("。", x24, 0xff333333).
                build();
    }

    private Spanned getTextBottomTips(String money, String up_money) {
        return Spans.with(this).font("满足其中一个条件即可成为金卡会员：\n1.购买会员升级套餐，需要支付 ", x24, 0xff333333).
                font(money, x24, 0xffFB5E01).style(Typeface.BOLD).
                font("元；\n2.在本平台进行油卡即时充值或购买加油套餐实际付款累计总额达到 ", x24, 0xff333333).
                font(up_money, x24, 0xffFB5E01).style(Typeface.BOLD).
                font("元整(折扣金额不算入内)。", x24, 0xff333333).
                build();
    }

    private Spanned getTextBottomTipsThree(String money, String up_money, String sub_money) {
        String last_money = Arith.sub(Double.valueOf(money), Double.valueOf(sub_money)) + "";
        return Spans.with(this).font("满足其中一个条件即可成为金卡会员：\n1.当您的当前身份是银卡会员时，直接购买铂金会员升级套餐，需要支付 ", x24, 0xff333333).
                font(money, x24, 0xffFB5E01).style(Typeface.BOLD).
                font("元；\n2.当您的当前身份是金卡会员时，购买铂金会员升级套餐，则只需要支付差价 ", x24, 0xff333333).
                font(sub_money, x24, 0xffFB5E01).style(Typeface.BOLD).
                font("元(" + money.replace(".00", "") + "元-" + last_money.replace(".0", "") + "元=" + sub_money.replace(".00", "") + "元);", x24, 0xff333333).
                font("\n3.在本平台进行油卡即时充值或购买加油套餐实际付款累计总额达到 ", x24, 0xff333333).
                font(up_money, x24, 0xffFB5E01).style(Typeface.BOLD).
                font("元整(折扣金额不算入内)。", x24, 0xff333333).
                build();
    }

    public void getOrderDelete(String order_number) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        VipOrderDetailBean bean = new VipOrderDetailBean();
        bean.order_number = order_number;
        Api.api_service.getVipOrderDelete(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "删除成功");
                    finish();
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BuyVipUpSuccessEvent event) {
        finish();
    }


    @OnClick({R.id.btn_back, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_submit:
                if (UI.toString(btnSubmit).equals("去付款")) {
//                    getPaymentList();
                    Intent intent = new Intent(this, VipOrderPayMoneyActivity.class);
                    intent.putExtra("pay_money", totalData.pay_money);
                    intent.putExtra("order_no", totalData.order_number);
                    intent.putExtra("level_id", totalData.level.id);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);

                } else if (UI.toString(btnSubmit).equals("删除订单")) {
                    getOrderDelete(order_no);
                } else if (UI.toString(btnSubmit).equals("油卡充值")) {
                    Util.startActivity(this, PacketRechargeActivity.class);
                }
                break;
        }
    }


}
